# -*- coding: utf-8 -*-
# @Time    : 2024/5/16 15:30
# @Author  : Alvin
# @File    : db_service.py

import pymysql
from pymysql.err import Error
import json
import os
GLOBAL_HOST = os.getenv('GLOBAL_HOST', 'localhost')

class Database:
    def __init__(self, config):
        self.connection = pymysql.connect(**config)

    def execute(self, query, params=None):
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(query, params or ())
                self.connection.commit()
                return cursor.rowcount
        except Error as e:
            self.connection.rollback()
            raise e

    def fetchone(self, query, params=None):
        try:
            with self.connection.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute(query, params or ())
                result = cursor.fetchone()
                if result:
                    result = self._process_result(result)
                return result
        except Error as e:
            raise e

    def fetchall(self, query, params=None):
        try:
            with self.connection.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute(query, params or ())
                results = cursor.fetchall()
                results = [self._process_result(result) for result in results]
                return results
        except Error as e:
            raise e

    def insert_one(self, table, data):
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        query = f"INSERT INTO {table} ({keys}) VALUES ({values})"
        return self.execute(query, list(data.values()))

    def insert_many(self, table, data_list):
        if not data_list:
            return 0

        keys = ', '.join(data_list[0].keys())
        values = ', '.join(['%s'] * len(data_list[0]))
        placeholders = ', '.join([f"({values})"] * len(data_list))
        query = f"INSERT INTO {table} ({keys}) VALUES {placeholders}"
        params = [value for data in data_list for value in data.values()]
        return self.execute(query, params)

    def update(self, table, data, condition, params=None):
        set_clause = ', '.join([f"{key} = %s" for key in data.keys()])
        query = f"UPDATE {table} SET {set_clause} WHERE {condition}"
        update_params = list(data.values())
        if params:
            update_params.extend(params)
        return self.execute(query, update_params)

    def delete(self, table, condition, params=None):
        query = f"DELETE FROM {table} WHERE {condition}"
        return self.execute(query, params)
    def close(self):
        self.connection.close()

    def _process_result(self, result):
        # 将 JSON 字符串转换为 Python 对象
        json_fields = ['img_url_list', 'tag_list','params']
        for field in json_fields:
            if field in result and isinstance(result[field], str):
                result[field] = json.loads(result[field])
        return result


# 配置数据库连接信息
class Config:
    DATABASE = {
        'host': GLOBAL_HOST,
        # 如果实在本地运行则设置port为3307,以便和本地mysql冲突
        # 'port' : 3307,
        'user': 'alvin',
        'password': '123456',
        'db': 'auto_scrapy',
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }